package wang.moshu.smvc.demo.intercept;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import wang.moshu.smvc.demo.constant.ReturnCode;
import wang.moshu.smvc.demo.constant.SessionConstants;
import wang.moshu.smvc.framework.exception.BusinessException;
import wang.moshu.smvc.framework.interceptor.RequestInterceptor;

/**
 * 执行时间拦截器
 * 
 * @author dingxiangyong 2016年8月12日 下午2:49:58
 */
@Component
public class LoginInterceptor implements RequestInterceptor
{
	private Log logger = LogFactory.getLog(LoginInterceptor.class);

	@Override
	public String description()
	{
		return "登录拦截器";
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		Object objUser = request.getSession(true).getAttribute(SessionConstants.SESSION_USER);

		if (objUser == null)
		{
			if (logger.isDebugEnabled())
			{
				logger.debug("登录拦截器拦截到未登录");
			}

			// 拦截器中出现异常，直接抛出异常即可终止接下来的接口调用
			throw new BusinessException(ReturnCode.NO_LOGIN, "请先登录");

			// 也可已返回false来终止流程
			// return false;
		}

		// 如果已经登陆，则返回true
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object returnObj) throws Exception
	{
	}

	@Override
	public void commitHandle(HttpServletRequest request, HttpServletResponse response)
	{
	}

}
